/**
 * 统一封装请求
 * 1、处理时间日期字段
 * 2、处理返回数据格式
 * **/

import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import type { AppResponse } from '@common/types/public.http';

import { ApiResponse } from '@common/utils/api-response.util';

@Injectable()
export class ResponseFormatInterceptor<T>
  implements NestInterceptor<T, AppResponse<T>>
{
  intercept(
    context: ExecutionContext,
    next: CallHandler,
  ): Observable<AppResponse<T>> {
    return next.handle().pipe(
      map((data) => {
        // 如果 data 已经是 ApiResponse 的格式，则直接返回
        if (data && typeof data === 'object' && 'success' in data && 'code' in data) {
          return data as AppResponse<T>;
        }

        return ApiResponse.success(data);
      }),
    );
  }
}
